/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package crawler;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import businesslogic.AnalyzedPage;
import businesslogic.GSAT;
import businesslogic.Util;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.url.WebURL;

/**
 * @author Yasser Ganjisaffar <lastname at gmail dot com>
 */
public class MyBasicCrawler extends WebCrawler {

		//resources matching this pattern will not be visited
        private final static Pattern FILTERS = Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g" + "|png|tiff?|mid|mp2|mp3|mp4"
                        + "|wav|avi|mov|mpeg|ram|m4v|pdf" + "|rm|smil|wmv|swf|wma|zip|rar|gz))$");

        /**
         * You should implement this function to specify whether the given url
         * should be crawled or not (based on your crawling logic).
         */
        @Override
        public boolean shouldVisit(WebURL url) {
                String href = url.getURL().toLowerCase();
                String parentURL = url.getParentUrl();
                //visit only pages that don't match the above filters and that are in the same web domain
                return !FILTERS.matcher(href).matches() && (parentURL == null || parentURL.contains(url.getDomain()));
        }

        /**
         * This function is called when a page is fetched and ready to be processed
         * by your program.
         */
        @Override
        public void visit(Page page) {
                String url = page.getWebURL().getURL();
                System.out.println("URL: " + url);

                BasicCrawlController.urlAddresses.add(url); 
                
//                String text = "";
                String html = "";
                if (page.getParseData() instanceof HtmlParseData) {
                        HtmlParseData htmlParseData = (HtmlParseData) page.getParseData();
//                        text = htmlParseData.getText();
                        html = htmlParseData.getHtml();
                        BasicCrawlController.htmlPages.add(html);
                }
                
                List<String> talkbacks = Util.getTalkbackFromHaaretz(html);
//        		System.out.println(talkbacks);
        		if(talkbacks.size() > 0){
        			String theText = "";
        			try {
    					theText = Util.getMainTextFromURL(GSAT.alchemyObj, url);
    					System.out.println(theText);
    				} catch (XPathExpressionException | SAXException | ParserConfigurationException e) {
    					e.printStackTrace();
    				}
        			Document doc = null;
        			//Analyze the given URL according to the given parameters
        			try{
        				doc = GSAT.alchemyObj.URLGetRankedNamedEntities(url, GSAT.entityParams);
        			}
        			catch(IOException | XPathExpressionException | SAXException | ParserConfigurationException err) {
        				System.out.println(err);
        			}
        			//System.out.println(Util.getStringFromDocument(doc));
        			
        			//save and load the extracted information 
        			String whatToExtract = "Person";
        			String modifiedUrlAddress = url.replaceAll("/", "_"); 
        			modifiedUrlAddress = modifiedUrlAddress.replaceAll(":", "_");
        			Util.createAnalyzedPage(doc, url, whatToExtract, theText, talkbacks);

        		}
        }
}